package jsontool;

import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JSONToolDemo {
    public static <T> String oneBeanToJson(T bean) {
        try {
            //1.数据校验
            if (bean == null){
                return "{}";
            }
            //2.获取字节码对象
            Class clazz = bean.getClass();
            //3.获取每一个属性
            Field[] fields = clazz.getDeclaredFields();
            //4.准备拼接的字符串
            StringBuilder sb = new StringBuilder();
            sb.append("{");//拼接开始
            //5.遍历获取属性值
            for (Field fieldName : fields) {
                //6.获取属性值
                 fieldName.setAccessible(true);//暴力访问
                Object beanValue =  fieldName.get(bean);
                //7.判断要加引号的属性
                if ( fieldName.getType() == String.class|| fieldName.getType() == StringBuffer.class|| fieldName.getType() == StringBuilder.class){
                    beanValue = "\""+beanValue+"\"";
                }

                //8.要忽略的注解，和要更改的注解
                //忽略序列化
                //注意：注解是写在字段上的，所以这里直接调用即可 fieldName.isAnnotationPresent(.class)
                if ( fieldName.isAnnotationPresent(MyJsonIgnore.class)|| fieldName.getName().equals("serialVersionUID")){
                    continue;
                }
                if ( fieldName.isAnnotationPresent(MyJsonFormat.class)){
                    //获取注解
                    MyJsonFormat annotation =  fieldName.getAnnotation(MyJsonFormat.class);
                    String s = annotation.pattern();
                    //格式化时间
                    beanValue = new SimpleDateFormat(s).format(beanValue);
                    beanValue = "\""+beanValue+"\"";
                }
                sb.append("\""+ fieldName.getName()+"\":"+beanValue+",");
            }
            sb.deleteCharAt(sb.length()-1);
            sb.append("}");
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Student s = new Student("张三",18,"男","语文",66,new Date());
        System.out.println(oneBeanToJson(s));

    }
//    @Test
//    public void Test(){
//        Student s = new Student("张三",18,"男",new String[]{"语文","数学","英语"},new Integer[]{99,88,66},new Date());
//        System.out.println(s);
//    }
}
